﻿using MyModule.Breeding;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace MyModule.ManageSheep
{
    public class DeathInfoService : ApplicationService, IDeathInfoService
    {
        private readonly IRepository<DeathInfo, int> _weighInfoRepository;
        private readonly IRepository<VarietyInfo, int> _varietyInfoRepository;
        private readonly IRepository<Dreproduction, int> _dreproductionRepository;
        private readonly IRepository<CauseInfo, int> _causeInfoRepository;
        private readonly IHttpClientFactory _httpClientFactory;

        public DeathInfoService(IRepository<DeathInfo, int> weighInfoRepository, IRepository<VarietyInfo, int> varietyInfoRepository, IRepository<Dreproduction, int> dreproductionRepository, IRepository<CauseInfo, int> causeInfoRepository, IHttpClientFactory httpClientFactory)
        {
            _weighInfoRepository = weighInfoRepository;
            _varietyInfoRepository = varietyInfoRepository;
            _dreproductionRepository = dreproductionRepository;
            _causeInfoRepository = causeInfoRepository;
            _httpClientFactory = httpClientFactory;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="deathDTO"></param>
        /// <returns></returns>
        public async Task<ResultDto<DeathDTO>> CreateAsync(DeathDTO deathDTO)
        {
            var list = await _weighInfoRepository.FirstOrDefaultAsync(x => x.Earbugles == deathDTO.Earbugles);
            if (list == null)
            {
                DeathInfo deathInfo = new DeathInfo();
                deathInfo.Earbugles = deathDTO.Earbugles;
                deathInfo.Cid = deathDTO.Cid;
                deathInfo.Vid = deathDTO.Vid;
                deathInfo.Dsex = deathDTO.Dsex;
                deathInfo.Dbuildings = deathDTO.Dbuildings;
                deathInfo.Columns = deathDTO.Columns;
                deathInfo.Ddate = deathDTO.Ddate;
                deathInfo.Rid = deathDTO.Rid;
                var result = await _weighInfoRepository.InsertAsync(deathInfo);
                var listCount = ObjectMapper.Map<DeathInfo, DeathDTO>(result);
                if (listCount != null)
                {
                    return new ResultDto<DeathDTO>() { Code = 200, Message = "添加成功" };
                }
                else
                {
                    return new ResultDto<DeathDTO>() { Code = 500, Message = "添加失败" };
                }
            }
            else
            {
                return new ResultDto<DeathDTO>() { Code = 501 };
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Did"></param>
        /// <returns></returns>
        public async Task DeleteAsync(int Did)
        {
            await _weighInfoRepository.DeleteAsync(Did);
        }
        /// <summary>
        ///死亡原因
        /// </summary>
        /// <returns></returns>
        public  async Task<List<CauseInfoDTO>> GetCauseInfoAsync()
        {
            var result = await _causeInfoRepository.GetListAsync();
            return ObjectMapper.Map<List<CauseInfo>, List<CauseInfoDTO>>(result);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<DeathVarietCauseDTO>> GetListAppAsync(string? Earbugles,int Cid)
        {
            var result = await _weighInfoRepository.ToListAsync();
            var varietie = await _varietyInfoRepository.ToListAsync();
            var dreproduction = await _dreproductionRepository.ToListAsync();
            var causes = await _causeInfoRepository.ToListAsync();
            var list = (from a in result
                        join c in varietie on a.Vid equals c.Id
                        join d in dreproduction on a.Rid equals d.Id
                        join e in causes on a.Cid equals e.Id
                        select new DeathVarietCauseDTO
                        {
                             Id = a.Id,
                             Earbugles = a.Earbugles,
                             Cid  = e.Id,
                             Vid  = c.Id,
                             Dsex = a.Dsex,
                             Dbuildings = a.Dbuildings,
                             Columns = a.Columns,
                             Ddate = a.Ddate,
                             Rid = d.Id,
                             Cname  = e.Cname,
                             Vname = c.Vname,
                             Rname = d.Rname
                        }).ToList();
            if (!string.IsNullOrEmpty(Earbugles))
            {
                list = list.Where(x => x.Earbugles == Earbugles).ToList();
            }
            if (Cid != 0)
            {
                list = list.Where(x => x.Cid == Cid).ToList();
            }
            return list.OrderByDescending(x => x.Id).ToList();
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<DeathDTO> GetListAsync(int id)
        {
            var result = await _weighInfoRepository.FirstOrDefaultAsync(x => x.Id == id);
            return ObjectMapper.Map<DeathInfo, DeathDTO>(result);
        }

        /// <summary>
        /// //更新
        /// </summary>
        /// <param name="deathDTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResultDto<DeathDTO>> UpdateAsync(DeathDTO deathDTO)
        {
                var result = await _weighInfoRepository.FindAsync(deathDTO.Id);
                if (result == null)
                {
                    return new ResultDto<DeathDTO>() { Code = 500 };
                }
                ObjectMapper.Map(deathDTO, result);
                var count = await _weighInfoRepository.UpdateAsync(result);
                var listCount = ObjectMapper.Map<DeathInfo, DeathDTO>(count);
                if (listCount != null)
                {
                    return new ResultDto<DeathDTO>() { Code = 200, Message = "修改成功" };
                }
                else
                {
                    return new ResultDto<DeathDTO>() { Code = 500, Message = "修改失败" };
                }
        }

        /// <summary>
        /// 淘汰耳号下拉框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<DropdownItemDto>> GetDeathEarbugles()
        {
            var client = _httpClientFactory.CreateClient();
            // 发送 HTTP 请求获取数据
            var response = await client.GetAsync("https://localhost:44336/api/app/earoverbit/earoverbits");
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to fetch data from the API.");
            }
            // 读取响应内容并反序列化
            var jsonString = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject<List<EarOverbit>>(jsonString);
            // 查询已使用的数据的 Id 列表
            var usedDataIds = _weighInfoRepository.GetListAsync().Result.Select(d => d.Earbugles).ToList();
            // 查询所有数据，并过滤已使用的数据
            var list = data.Where(d => !usedDataIds.Contains(d.OverbitName)).ToList();
            // 转换为 DropdownItemDto 并返回
            return list.Select(d => new DropdownItemDto { Id = d.Id, Name = d.OverbitName }).ToList();
        }
    }
}
